package com.ktwlsoft.fundmanage.domain.entity;

import javax.persistence.*;
import javax.validation.constraints.*;

import com.ktwlsoft.fundmanage.domain.entity.pictureconfig.SignCredential;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 资金受理业务
 *
 * @author lanjian
 * @version 1.0
 */
@ApiModel
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames="netSignCode")})
@Data
public class FundSuperviseAccept extends BaseEntity {

    private static final long serialVersionUID = -2646158504677369745L;

    public FundSuperviseAccept() {

    }

    public FundSuperviseAccept(final long tsCode, final ContractApproval contractApproval, final AcceptState acceptState,
            final String districtCode) {
        this.tsCode = tsCode;
        this.contractApproval = contractApproval;
        this.acceptState = acceptState;
        this.districtCode = districtCode;
    }

    public void init() {
        // IAccountUser user = UserUtils.getUser();
        // this.setUserName(user != null ? user.getName() : "unknown");
        // this.setUserId(user != null ? user.getUserId() : "unknown");
        this.downAmount = this.superviseAmount.subtract(this.loanAmount);
    }

    @ApiModelProperty("案件编号")
    @Id
    @Column(name = "ts_code", columnDefinition = "bigint(30) NOT NULL COMMENT '交易编号'")
    private long tsCode;

    @ApiModelProperty("工作流id")
    @Column(name = "flowInstanceId", columnDefinition = "varchar(20) default null comment '工作流实例id'")
    private String flowInstanceId;

    @ApiModelProperty("合同审核是否通过")
    @Column(name = "contract_approval", columnDefinition = "varchar(30) default 'START' comment '合同状态' ")
    @Enumerated(EnumType.STRING)
    private ContractApproval contractApproval = ContractApproval.WAITING;

    @ApiModelProperty("合同审核人")
    @Column(name = "contract_auditor", length = 20, columnDefinition = "varchar(20) default null comment '合同审核人'")
    private String contractAuditor;

    @ApiModelProperty("合同审核人Id")
    @Column(name = "contract_auditor_id", length = 100, columnDefinition = "varchar(30) default null comment '合同审核人id'")
    private String contractAuditorId;

    @ApiModelProperty("是否贷款")
    @Column(name = "loan_exist", columnDefinition = "bit default 0 comment '是否贷款'")
    private boolean loanExist = false;

    @ApiModelProperty("是否存在抵押")
    @Column(name = "guarenty_exist", columnDefinition = "bit default 0 comment '是否存在抵押'")
    private boolean guarentyExist = false;

    @ApiModelProperty("房屋性质，不得超过30字符")
    @Column(length = 30, columnDefinition = "varchar(30) default null comment '房屋性质'")
    private String houseProperty;

    @ApiModelProperty("监管账户，请不要超过40字符")
    @Column(name = "supervise_bank", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '监管账户'")
    @Size(max = 40, message = "不要超过40字符")
    private String superviseBank;

    @ApiModelProperty("买方银行账户，请不要操作40字符")
    @Column(name = "buyer_bank_account", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '买方银行账户'")
    @Size(max = 40, message = "不要超过40字符")
    private String buyerBankAccount;

    @ApiModelProperty("买方贷款银行")
    @Column(length = 20, columnDefinition = "varchar(20) default null comment '买方贷款银行'")
    private String buyerLoanBank;

    @ApiModelProperty("贷款金额")
    @Column(name = "loan_amount", columnDefinition = "decimal(16,8) DEFAULT 0 COMMENT '贷款金额'")
    private BigDecimal loanAmount = BigDecimal.ZERO;

    @ApiModelProperty("监管金额")
    @Column(name = "supervise_amount", columnDefinition = "decimal(16,8) DEFAULT 0 COMMENT '监管金额'")
    private BigDecimal superviseAmount = BigDecimal.ZERO;

    @ApiModelProperty("合同金额")
    @Column(name = "contract_amount", columnDefinition = "decimal(16,8) DEFAULT 0 COMMENT '合同金额'")
    private BigDecimal contractAmount = BigDecimal.ZERO;

    @ApiModelProperty("贷款期限（年）0~30")
    @Column(name = "loan_period", columnDefinition = "tinyint(4) DEFAULT 0 COMMENT '贷款期限'")
    @Max(value = 30)
    @Min(value = 0)
    private int loanPeriod = 0;

    @ApiModelProperty("挂牌编号，请不要超过40字符")
    @Column(name = "pub_code", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '挂牌编号'")
    @Size(max = 40, message = "不得大于40字符")
    private String pubCode;

    @ApiModelProperty("所有权证号, 不要大于30字符")
    @Column(name = "ownership_no", columnDefinition = "varchar(30) DEFAULT NULL COMMENT '所有权证号'")
    @Size(max = 30, message = "所有权证号，不要大于30字符")
    private String ownershipNo;

    @ApiModelProperty("所有权证号-旧, 不要大于30字符")
    @Column(name = "old_ownership_no", columnDefinition = "varchar(30) DEFAULT NULL COMMENT '所有权证号-旧'")
    @Size(max = 30, message = "所有权证号-旧，不要大于30字符")
    private String oldOwnershipNo;

    @ApiModelProperty("房屋编号, 不超过40字符")
    @Column(name = "house_code", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '房屋编号'")
    @Size(max = 40, message = "房屋编号, 不超过40字符")
    private String houseCode;

    @ApiModelProperty("房屋所在区县代码，不得超过40字符")
    @Column(name = "district_code", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '房屋所在区县代码'")
    @Size(max = 40, message = "房屋所在区县代码，不得超过40字符")
    private String districtCode;

    @ApiModelProperty("房屋坐落位置，不得超过40字符")
    @Column(name = "house_address", columnDefinition = "varchar(40) DEFAULT NULL COMMENT '房屋坐落位置'")
    @Size(max = 40, message = "房屋坐落位置，不得超过40字符")
    private String houseAddress;

    @ApiModelProperty("房屋用途，不得超过40字符")
    @Column(name = "use_range", length = 40, columnDefinition = "varchar(40) default null comment '房屋用途'")
    @Size(max = 40, message = "房屋用途，不得超过40字符")
    private String useRange;

    @ApiModelProperty("房屋建筑面积")
    @Column(columnDefinition = "decimal(12,3) DEFAULT 0 COMMENT '房屋建筑面积'")
    private BigDecimal constructionArea = BigDecimal.ZERO;

    @ApiModelProperty("房屋套内面积")
    @Column(columnDefinition = "decimal(12,3) DEFAULT 0 COMMENT '房屋套内面积'")
    private BigDecimal comprisingArea = BigDecimal.ZERO;

    @ApiModelProperty("房屋共有建筑面积")
    @Column(columnDefinition = "decimal(12,3) DEFAULT 0 COMMENT '房屋共有建筑面积'")
    private BigDecimal commonArea = BigDecimal.ZERO;

    @ApiModelProperty("房屋结构，不得超过100字符")
    @Column(name = "structure", columnDefinition = "varchar(100) DEFAULT NULL COMMENT '房屋结构'")
    @Size(max = 100, message = "房屋结构，不得超过100字符")
    private String structure;

    @ApiModelProperty("经办人Id，不得超过50字符")
    @Column(name = "user_id", columnDefinition = "varchar(50) default null comment '经办人id'")
    private String userId;

    @ApiModelProperty("经办人姓名，不得超过30字符")
    @Column(name = "user_name", columnDefinition = "varchar(30) default null comment '经办人姓名'")
    private String userName;

    @ApiModelProperty("打印次数")
    @Column(name = "print_times", columnDefinition = "tinyint(4) DEFAULT 0 COMMENT '打印次数'")
    @Max(value = 30)
    @Min(value = 0)
    private int printTimes = 0;

    @ApiModelProperty("是否过户")
    @Column(name = "transfer_state", columnDefinition = "bit DEFAULT 0 COMMENT '是否过户'")
    private boolean transferState = false;

    @ApiModelProperty("是否自动过户")
    @Column(columnDefinition = "bit DEFAULT 0 COMMENT '是否自动过户'")
    private boolean isAutoTransfer = false;

    @ApiModelProperty("是否备案")
    @Column(name = "record_state", columnDefinition = "bit DEFAULT 0 COMMENT '是否备案'")
    private boolean recordState = false;

    @ApiModelProperty("资金状态")
    @Enumerated(EnumType.STRING)
    @Column(name = "fund_state", columnDefinition = "varchar(30) default null comment '资金状态'")
    private FundState fundState;

    @ApiModelProperty("还款方式")
    @Enumerated(EnumType.STRING)
    @Column(name = "repayment_means", columnDefinition = "varchar(30) default null comment '还款方式'")
    private RepaymentMeans repaymentMeans;

    @ApiModelProperty("案件状态")
    @Enumerated(EnumType.STRING)
    @Column(name = "accept_state", columnDefinition = "varchar(30) default 'HANDING' comment '案件状态'")
    private AcceptState acceptState = AcceptState.HANDING;

    @ApiModelProperty("备案状态")
    @Enumerated(EnumType.STRING)
    @Column(length = 30)
    private ReferenceState referenceState = ReferenceState.UNREFERENCED;

    @ApiModelProperty("备案号")
    @Column(length = 40)
    private String referenceCode;

    @ApiModelProperty("备案操作人")
    @Column(length = 40)
    private String referenceHandleUserName;

    @ApiModelProperty("备案操作人id")
    @Column(length = 40)
    private String referenceHandleUserId;

    @ApiModelProperty("不动产单元号")
    @Column(length = 40)
    private String immovablesUnitNum;

    @ApiModelProperty("房屋编号")
    @Column(length = 40)
    private String houseNumber;

    @ApiModelProperty("合同url，多张图片用‘|’分割")
    @Column(length = 200)
    private String contractUrl;

    @ApiModelProperty("监管协议url，多张图片用‘|’分割")
    @Column(length = 200)
    private String superviseProtocolUrl;

    @ApiModelProperty("卖方身份证url，多张图片用‘|’分割")
    @Column(length = 200)
    private String sellerIdCardUrl;

    @ApiModelProperty("卖方上市准入证url，多张图片用‘|’分割")
    @Column(length = 200)
    private String sellerAccessCertificationUrl;

    @ApiModelProperty("卖方不动产权url，多张图片用‘|’分割")
    @Column(length = 200)
    private String sellerPropertyRightUrl;

    @ApiModelProperty("买方身份证url，多张图片用‘|’分割")
    @Column(length = 200)
    private String buyerIdCardUrl;

    @ApiModelProperty("买方不动产权url，多张图片用‘|’分割")
    @Column(length = 200)
    private String buyerPropertyRightUrl;

    @ApiModelProperty("买方婚姻url")
    @Column(length = 200)
    private String buyerMarryUrl;

    @ApiModelProperty("是否限制")
    private boolean limited = false;

    @ApiModelProperty("是否查封登记")
    private boolean limitReg = false;

    @ApiModelProperty("是否抵押备案")
    private boolean mortgageFiling = false;

    @ApiModelProperty("是否抵押登记")
    private boolean mortgageReg = false;

    @ApiModelProperty("买卖合同号")
    @Column(length = 30, columnDefinition = "varchar(30) default null comment '买卖合同号'")
    private String contractCode;

    @ApiModelProperty("挂牌号")
    @Column(length = 30, columnDefinition = "varchar(30) default null comment '挂牌号'")
    private String handoutCode;

    @ApiModelProperty("可划款金额")
    @Column(columnDefinition = "decimal(16,8) DEFAULT 0 comment '可划款金额'")
    private BigDecimal amountLeft = BigDecimal.ZERO;

    @ApiModelProperty("备注")
    @Column(length = 50, columnDefinition = "varchar(30) default null comment '备注'")
    private String remark;

    @Enumerated(EnumType.STRING)
    @ApiModelProperty("案件退款状态，仅当案件退款时有效")
    @Column(columnDefinition = "varchar(50) default 'NORMAL' comment '退款状态'")
    private RefundState refundState = RefundState.NORMAL;

    @ApiModelProperty("是否曾退回")
    @Transient
    private Boolean isReturn;

    @Transient
    @ApiModelProperty("要件信息")
    private List<SignCredential> signCredentials;

    @ApiModelProperty("卖方姓名")
    @Transient
    private String sellerName;

    @ApiModelProperty("入账集合")
    @Transient
    private List<FundInRecord> fundInRecords;

    @ApiModelProperty("退回人")
    @Transient
    private String cancelName;

    @ApiModelProperty("退回人id")
    @Transient
    private String cancelId;

    @ApiModelProperty("退回原因")
    @Transient
    private String cancelReson;

    @ApiModelProperty("退回时间")
    @Transient
    private Date cancelDate;

    @Transient
    @ApiModelProperty("房屋关系人集合")
    private List<HouseRelatedPerson> houseRelatedPersonList;

    @Transient
    @ApiModelProperty("划款单集合")
    private List<TransferApply> transferApplies;

    @Transient
    @ApiModelProperty("首付")
    private BigDecimal downAmount = BigDecimal.ZERO;

    @ApiModelProperty("锁定")
    private Boolean doLock = false;

    public boolean restore(final BigDecimal amount) {
        final BigDecimal result = this.amountLeft.add(amount);
        if (this.superviseAmount.compareTo(result) < 0) {
            return false;
        } else {
            // setAmountLeft(result);
            return true;
        }
    }

    public boolean transfer(final BigDecimal amount) {
        final BigDecimal result = this.amountLeft.subtract(amount);
        if (result.compareTo(BigDecimal.ZERO) < 0) {
            return false;
        } else {
            // setAmountLeft(result);
            return true;
        }
    }

    /**
     * 资金状态
     */
    public enum FundState {

        /**
         * 未缴费
         */
        UNPAID("未缴"),
        /**
         * 未缴清
         */
        NOT_PAID_ALL("未缴清"),
        /**
         * 首付款未缴
         */
        DOWN_NOT_PAID("首付未缴"),
        /**
         * 首付未缴清
         */
        DOWN_NOT_PAID_ALL("首付未缴清"),
        /**
         * 贷款未缴
         */
        LOAN_NOT_PAID("贷款未缴"),
        /**
         * 贷款未缴清
         */
        LOAN_NOT_PAID_ALL("贷款未缴清"),
        /**
         * 资金已交付完成
         */
        DONE("完成");

        @Getter
        private String name;

        FundState(final String name) {
            this.name = name;
        }
    }

    /**
     * 还款方式
     */
    public enum RepaymentMeans {
        /**
         * 等额本息
         */
        ACPI("等额本息"),
        /**
         * 等额本金
         */
        AC("等额本金");

        @Setter
        private String name;

        RepaymentMeans(final String name) {
            this.name = name;
        }
    }

    /**
     * 案件状态
     */
    public enum AcceptState {
        /**
         * 处理中
         */
        HANDING("处理中"),
        /**
         * 已撤销
         */
        CANCEL("已撤销/作废"),
        /**
         * 完成
         */
        FINISH("完成");

        private String name;

        AcceptState(final String name) {
            this.name = name;
        }
    }

    /**
     * 合同审核状态
     */
    public enum ContractApproval {
        /**
         * 起始
         */
        START("起始"),
        /**
         * 待审核
         */
        WAITING("待审核"),
        /**
         * 通过
         */
        PASS("通过"),
        /**
         * 未通过
         */
        UNPASS("未通过");

        /**
         * 审核名称
         */
        private String name;

        ContractApproval(final String name) {
            this.name = name;
        }
    }

    /**
     * 备案状态
     */
    public enum ReferenceState {
        /**
         * 未备案
         */
        @ApiModelProperty("未备案")
        UNREFERENCED,

        /**
         * 已备案
         */
        @ApiModelProperty("已备案")
        REFERENCED;
    }

    /**
     * 退款单状态，仅针对案件做退款处理时有效
     */
    public enum RefundState {
        /**
         * 正常/待退款（仅对退款有效）
         */
        NORMAL("正常/待退款"),
        /**
         * 待上传, 当打印退款单以后，就设置状态为待上传（仅对退款有效）
         */
        WAIT_UPLOAD("待上传"),
        /**
         * 待开具，当上传完以后，就设置为待开具（仅对退款有效）
         */
        WAIT_TRANSFER("待开具"),
        /**
         * 回退
         */
        CANCEL("回退"),
        /**
         * 退回处理（作废）
         */
        CANCEL_HANDED("退回处理"),
        /**
         * 未审核/待审核
         */
        WAIT_AUTH("未审核"),
        /**
         * 审核通过
         */
        PASSED("审核通过"),
        /**
         * 审核未通过
         */
        UNPASSED("审核未通过"),
        /**
         * 已划拨
         */
        GRANTED("已划拨");

        String name;

        RefundState(final String name) {
            this.name = name;
        }
    }
}
